package repository;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;

import play.db.jpa.JPA;
import play.libs.F.Function0;
import prefix.util.JPAUtil;

import models.Doc;
import models.DocFile;
import models.Doc.Category;
import service.ActorService;
import service.DocFileService;
import service.DocService;
import service.LoanAppService;
import service.impl.DocFileServiceImpl;
import service.impl.DocServiceImpl;

public class DocRepository extends AbstractRepository {

    public DocRepository() {
        super();
        // TODO Auto-generated constructor stub
    }

    public static DocService getDocByType(Integer aid, Doc.Type type) {
        Doc tldoc = getSingleByProperties(Doc.class, new String[] { "aid", "type" },
                new Object[] { aid, type.ordinal() });
        if (tldoc != null) {
            return new DocServiceImpl(tldoc);
        }
        return null;
    }

    public static List<DocService> getDocByCategory(Integer aid, Category docCategory) {
        List<DocService> docs = new ArrayList<DocService>();
        List<Doc> tldocs = getListByProperties(Doc.class, new String[] { "aid", "category" }, new Object[] { aid,
                docCategory.ordinal() });
        if (tldocs != null) {
            for (Doc tldoc : tldocs) {
                DocService doc = new DocServiceImpl(tldoc);
                docs.add(doc);
            }
        }
        return docs;
    }

    /**
     * Get document by id
     * 
     * @throws Throwable
     */
    public static DocService getDocById(final Integer docId)  {
        Doc doc = JPAUtil.em().find(Doc.class, docId);
        if (doc != null) {
            return new DocServiceImpl(doc);
        }
        return null;
    }

    /**
     * Get uploaded file by id
     * 
     * @throws Throwable
     */
    public static DocFileService getDocFileById(final Integer docFileId) {
        DocFile docFile = JPAUtil.em().find(DocFile.class, docFileId);

        if (docFile != null) {
            return new DocFileServiceImpl(docFile);
        }
        return null;
    }

    /**
     * Get all files uploaded for a given document request
     * 
     * @throws Throwable
     */
    public static List<DocFileService> getUploadedFiles(Long docId) throws Throwable {
        List<DocFileService> files = new ArrayList<DocFileService>();
        List<DocFile> tlDocFiles = getListByProperty(DocFile.class, "docId", docId);
        if (tlDocFiles != null) {
            for (DocFile tlDocFile : tlDocFiles) {
                files.add(new DocFileServiceImpl(tlDocFile));
            }
        }
        return files;
    }

}
